{% include "GdsVenteBundle::BonLivraison/bon_to_fac_script.html.twig" %}
<div class="span12">
    <div class="box gradient">
        <div class="title" style="text-align: center">
            <h4>Facturation de  {{bonlivraison}}</h4>
        </div>

        <div class="content noPad clearfix">
            <table style="width: 100%">
                <tr>
                    <td style="width: 20%">
                        <label>Date:</label>
                        <div>
                            <input id="date" type="text" />
                            <input id="now" type="text" style="width: 70px;" readonly/>
                        </div>
                    </td>
                    <td  style="width: 20%">
                        <label>Client:</label>
                                    {{bonlivraison.client}}
                    </td>
                    <td  style="width: 20%">
                        <label>Departement:</label>
                            {{bonlivraison.departement}}
                    </td>
                    <td  style="width: 40%">
                        <label>Numero Facture:</label>
                                {{ reference}}
                    </td>
                </tr>
            </table>

        </div> 
    </div>
</div>
<div class="span12" style="margin-left:0">
    <table>
        <tr>
            <td id="td_articles">
                <input type="text" id="articles" style="width:100%"/>
            </td>
            <td style="width: 60%"></td>
            <td>Tolerance:</td>
            <td>
                <input type="text" id="tolerance" value="0.200" onkeyup="Test(this)" style="width:90%"/>
            </td>
        </tr>
    </table>
    <div class="box gradient">
        <div class="content noPad clearfix">
            <table id="table_facture" cellpadding="0" cellspacing="0" border="0" class="responsive  display table table-bordered" width="100%">
                <thead>
                    <tr >
                        <th>N°</th>
                        <th>Reference</th>
                        <th>Designation</th>
                        <th>Qte</th>
                        <th id="th_dispo" style="width:5%">Dispo</th>
                        <th>P.U.HT</th>
                        <th>TVA</th>
                        <th>Remise</th>
                        <th>P.U.TTC</th>
                        <th id="th_total" style="width:10%">Total</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="lignes_bon_livraison_to_facture">
                </tbody>
            </table>
        </div>
    </div>
    <div class="span2" style="margin-left:83%">
        <div class="content noPad clearfix">
            <table  border="1px" class="responsive  display table table-bordered" width="100%" style="border:#D0E9F5 ">
                <thead>
                    <tr style="width: 100%">
                        <th style="text-align: center;width: 50%">Ancien Montant</th>
                        <th id="montant_total_ancien"  style="width: 50%">0.000</th>
                    </tr>
                    <tr style="width: 100%">
                        <th style="text-align: center;width: 50%">Montant Total</th>
                        <th id="montant_total"  style="width: 50%">0.000</th>
                    </tr>
                    <tr>
                        <th style="text-align: center">Timbre</th>
                        <th id="timbre" >{{timbre|number_format(3)}}</th>
                    </tr>
                    <tr>
                        <th style="text-align: center">Total TTC</th>
                        <th id="montant_total_ttc" >{{timbre|number_format(3)}}</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>
    {# Ajout d'un lien pour ajouter un champ cat�gorie suppl�mentaire. #}
<div class="span2" style="margin-left:0">
    <h4 style="text-align: center">Taxe Inital</h4>
    <div class="box gradient">
        <div class="content noPad clearfix">
            <table id="taxe" cellpadding="0" cellspacing="0" border="0" class="responsive  display table table-bordered" width="100%">
                <thead>
                    <tr>
                        <th>Taxe</th>
                        <th>Base</th>
                        <th>Montant</th>
                    </tr>
                </thead>
                <tbody id="taxe_body">
                    <tr id="tr_taxe_18">
                        <td id="taxe_18">18%</td>
                        <td id="base_18">0.000</td>
                        <td id="montant_taxe_18">0.000</td>
                    </tr>
                    <tr>
                        <td>Totaux</td>
                        <td></td>
                        <td id="total_taxe">0.000</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<div class="span2" style="margin-right:0">
    <h4 style="text-align: center">Taxe Final</h4>
    <div class="box gradient">
        <div class="content noPad clearfix">
            <table id="taxe2" cellpadding="0" cellspacing="0" border="0" class="responsive  display table table-bordered" width="100%">
                <thead>
                    <tr>
                        <th>Taxe</th>
                        <th>Base</th>
                        <th>Montant</th>
                    </tr>
                </thead>
                <tbody id="taxe_body2">
                    <tr id="tr_taxe_18_2">
                        <td id="taxe_18_2">18%</td>
                        <td id="base_18_2">0.000</td>
                        <td id="montant_taxe_18_2">0.000</td>
                    </tr>
                    <tr>
                        <td>Totaux</td>
                        <td></td>
                        <td id="total_taxe2">0.000</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<div class="span2" style="margin-right: 0">
    <table>
        <tr>
            <td style="text-align: center">
                <input type="button" style="width:100px" id="submit_form_facture" value="Enregistrer" class="nostyle btn btn-success btn-large" />
            </td>
            <td style="text-align: center">
                <input type="button" style="width:100px" id="submit_form_facture_print" value="Imprimer" class="nostyle btn btn-success btn-large" />
            </td>
        </tr>
        <tr>
            <td style="height: 20px"></td>
        </tr>
        <tr>
            <td>
                <input id="retour2" style="width:100px" type="button" class="btn btn-info cut-icon-previous"  value="Retour" onclick="retourListeBonLivraison2()">
            </td>
        </tr>
    </table>
</div>
<script>
    document.documentElement.className += 'loadstate';
    $(document).ready(function() {
        $('#submit_form_facture').click(function() {
            $('#submit_form_facture').hide()
            $('#submit_form_facture_print').hide()
            if (Math.abs($('#td_reste').html()) > $('#tolerance').val()) {
                $.msgBox({
                    title: "Tolerance Inférieur au Reste !!!",
                    content: "Ajouter Des articles pour diminuer le reste",
                    type: "info",
                    buttons: [{value: "Ok"}],
                    success: function(result) {
                        $('#submit_form_facture').show("slow")
                        $('#submit_form_facture_print').show("slow")
                    }
                });
            } else {
                $.ajax({
                    url: '{{path('gds_vente_bon_livraison_facturer')}}',
                    type: "POST",
                    datatype: 'json',
                    data: 'all_articles={"articles":' + JSON.stringify(articles) + ',"articles_replaced":' + JSON.stringify(articles_replaced) + '}' + '&id=' + '{{id}}' + '&date=' + $('#date').val() + '&heure=' + $('#heure').val(),
                    success: function(data) {
                        if (data.success) {
                            $.msgBox({
                                title: "Facture",
                                content: "Enregistrement Effectué avec succés",
                                type: "info",
                                buttons: [{value: "OK"}],
                                success: function(result) {
                                    location.reload();
                                }
                            });
                        } else {
                            $.msgBox({
                                title: "Facture",
                                content: "Erreur D'enregistrement",
                                type: "error",
                                buttons: [{value: "OK"}],
                                success: function(result) {
                                    $('#submit_form_facture').show("slow")
                                    $('#submit_form_facture_print').show("slow")
                                }
                            });
                        }
                    },
                    error: function(e) {
                        $.msgBox({
                            title: "Facture",
                            content: "Erreur D'enregistrement",
                            type: "error",
                            buttons: [{value: "OK"}],
                            success: function(result) {
                                $('#submit_form_facture').show("slow")
                                $('#submit_form_facture_print').show("slow")
                            }
                        });
                    }
                })
            }
        })
        $('#submit_form_facture_print').click(function() {
            $('#submit_form_facture').hide()
            $('#submit_form_facture_print').hide()
            if (Math.abs($('#td_reste').html()) > $('#tolerance').val()) {
                $.msgBox({
                    title: "Tolerance Inférieur au Reste !!!",
                    content: "Ajouter Des articles pour diminuer le reste",
                    type: "info",
                    buttons: [{value: "Ok"}],
                    success: function(result) {
                        $('#submit_form_facture').show("slow")
                        $('#submit_form_facture_print').show("slow")
                    }
                });
            } else {
                $.ajax({
                    url: '{{path('gds_vente_bon_livraison_facturer')}}',
                    type: "POST",
                    datatype: 'json',
                    data: 'all_articles={"articles":' + JSON.stringify(articles) + ',"articles_replaced":' + JSON.stringify(articles_replaced) + '}' + '&id=' + '{{id}}' + '&date=' + $('#date').val() + '&heure=' + $('#heure').val(),
                    success: function(data) {
                        if (data.success) {
                            Imprimer(data.id)
                        } else {
                            $.msgBox({
                                title: "Facture",
                                content: "Erreur D'enregistrement",
                                type: "error",
                                buttons: [{value: "OK"}],
                                success: function(result) {
                                    $('#submit_form_facture').show("slow")
                                    $('#submit_form_facture_print').show("slow")
                                }
                            });
                        }
                    },
                    error: function(e) {
                        $.msgBox({
                            title: "Facture",
                            content: "Erreur D'enregistrement",
                            type: "error",
                            buttons: [{value: "OK"}],
                            success: function(result) {
                                $('#submit_form_facture').show("slow")
                                $('#submit_form_facture_print').show("slow")
                            }
                        });
                    }
                })
            }
        })
        reste_ttc = 0
        $('#date').datepicker();
        var fullDate = new Date();
        var twoDigitMonth = fullDate.getMonth()
        twoDigitMonth++
        twoDigitMonth += "";
        if (twoDigitMonth.length == 1)
            twoDigitMonth = "0" + twoDigitMonth;
        var twoDigitDate = fullDate.getDate() + "";
        if (twoDigitDate.length == 1)
            twoDigitDate = "0" + twoDigitDate;
        var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
        $("#date").val(currentDate)
        setInterval(time, 1000);
        index = 0;
        nb_article = 1;
        $container = $('#lignes_bon_livraison_to_facture');
        articles = new Array();
        articles_replaced = new Array();
        $.ajax({
            url: '{{path('gds_vente_get_all_articles')}}',
            datatype: 'json',
            data: 'raison_social=' + '{{bonlivraison.client}}',
            success: function(data) {
                $("#articles").tokenInput(data, {
                    preventDuplicates: true,
                    onAdd: function(item) {
                        $('.token-input-token').hide()
                        var article = getArticleReplaced(item.id)
                        if (!article) {
                            add_ligne()
                            var article = item.name.split(' : ');
                            var reference = article[0]
                            var designation = article[1]
                            item.quantite = 0
                            var id = index - 1
                            $('#td_reference_' + id).html(reference)
                            $('#td_designation_' + id).html(designation)
                            $('#gds_ventebundle_' + id + '_article').val(item.id)
                            var article = getArticle($('#gds_ventebundle_' + id + '_article').val())
                            if (article) {
                                item.remise = article.remise
                                $('#gds_ventebundle_' + id + '_taux_remise').spinner("destroy");
                                $('#gds_ventebundle_' + id + '_taux_remise').attr('disabled', true)
                            } else {
                                var remise_max = item.remise_max;
                                $('#gds_ventebundle_' + id + '_taux_remise').spinner({
                                    min: 0,
                                    max: remise_max,
                                    step: 1,
                                    places: 2,
                                    showOn: 'both'
                                });
                            }
                            articles_replaced.push(item)
                            remplir_ligne(id, item)
                            setQuantite(id)
                            $('#gds_ventebundle_' + id + '_quantite').keyup()
                        } else {
                            id = article.index
                        }
                    },
                });
                $("html").removeClass("loadstate");
            }
        })
    {% for l,ligne in lignes %}
        add_ligne_from_bl_blanc()
        var id = index - 1
        $('#td_reference_' + id).html('{{ligne.article.reference}}')
        $('#td_designation_' + id).html('{{ligne.article.designation}}')
        $('#td_qte_' + id).html('{{ligne.quantiteBlanc|number_format(2)}}')
        $('#td_prix_unitaire_ht_' + id).html('{{ligne.prixUnitaireHt}}')
        var tva_twig = {{ligne.tauxTva}}
        tva_twig = tva_twig.toFixed(2)
        $('#td_tva_' + id).html(tva_twig + '%')
        $('#td_remise_' + id).html('{{ligne.tauxRemise}}')
        $('#gds_ventebundle_' + id + '_article').val('{{ligne.article.id}}')
        var x = new Object();
        x.reference = $('#td_reference_' + id).html()
        x.designation = $('#td_designation_' + id).html()
        x.taux_tva = '{{ligne.tauxTva}}'
        x.remise = '{{ligne.tauxRemise}}'
        x.remise_max = '{{ligne.article.remiseMax}}'
        x.prix_vente = '{{ligne.prixUnitaireHt}}'
        x.quantite_blanc = '{{ligne.quantiteBlanc}}'
        x.quantite_noir = '{{ligne.quantiteNoir}}'
        x.quantite_blanc_begin = x.quantite_blanc
        x.quantite_noir_begin = x.quantite_noir
        x.prix_vente_min_ttc = x.prix_vente * (1 + (x.taux_tva / 100)) * (1 - (x.remise_max / 100))
        x.name = x.reference + ' : ' + x.designation
        x.id = '{{ligne.article.id}}'
        articles[articles.length] = x
        completerChamp(id)
        if ({{ligne.quantiteNoir}} > 0) {
            add_ligne_from_bl_noir()
            var id = index - 1
            $('#gds_ventebundle_' + id + '_quantite').spinner({
                min: 0,
                max: {{ligne.quantiteNoir}},
                step: 1,
                places: 2,
                showOn: 'both'
            });
            $('#tr_' + id).css('background-color', 'pink');
            $('#gds_ventebundle_' + id + '_quantite').val('{{ligne.quantiteNoir|number_format(2)}}')
            completerChampNoir(id)
        }
    {% endfor %}
        add_ligne_reste_ttc()
        resteTtc()
        getTaxeInitial()
        RefraichirTaxe()
        setTousQuantite()
    })
    function retourListeBonLivraison2() {
        $.ajax({
            url: "{{ path('gds_vente_liste_bon_livraison') }}",
            data: 'retour=true' + '&numero=' + lf[0] + '&client=' + lf[1] + '&date1=' + lf[2] + '&date2=' + lf[3] + '&heure1=' + lf[4] + '&heure2=' + lf[5]
                    + '&reference=' + lf[6] + '&designation=' + lf[7] + '&ttc1=' + lf[8] + '&ttc2=' + lf[9] + '&is_facturer=' + lf[10]
                    + '&reglement=' + lf[11] + '&departement=' + lf[12],
            success: function(data) {
                $('#div_liste_bon_livraison').replaceWith(data)
                $('#filtre_numero').val(lf[0])
                $('#client').val(lf[1])
                $('#filtre_date1').val(lf[2])
                $('#filtre_date2').val(lf[3])
                $('#filtre_reference').val(lf[6])
                $('#filtre_designation').val(lf[7])
                $('#filtre_ttc1').val(lf[8])
                $('#filtre_ttc2').val(lf[9])
                $('#filtre_type').val(lf[10])
                $('#filtre_reglement').val(lf[11])
                $('#departement').val(lf[12])
            }
        })
    }
    function add_ligne_reste_ttc() {
        var td_label = '<td colspan="4" style="text-align:center"><h4>Reste TTc</h4></td>'
        var td_reste = '<td colspan="7" style="text-align:center"><h4 id="td_reste">0.000</h4></td>'
        var tr = $('<tr id="tr_reste">' + td_label + td_reste + '</tr>')
        $container.append(tr)
    }
    function add_ligne() {
        var td_num = '<td class="numero_ligne" style="padding:0;text-align:center" id="td_num_' + index + '">' + nb_article + '</td>';
        var hidden_stock = '<input id="gds_ventebundle_' + index + '_article" type="hidden"/>';
        var td_reference = '<td style="padding:0;width:10%" id="td_reference_' + index + '"></td>';
        var td_designation = '<td style="padding:0;width:30%" id="td_designation_' + index + '"></td>';
        var td_qte = '<td style="padding:0;width:10%" id="td_qte_' + index + '"><input style="padding:2%;width:80%" type="text" id="gds_ventebundle_' + index + '_quantite" type="text" value="0" onkeyup="Test(this)"></td>';
        var td_qte_dispo = '<td style="padding:0" id="td_qte_dispo_' + index + '"></td>';
        var td_prix_unitaire_ht = '<td style="padding:0" id="td_prix_unitaire_ht_' + index + '"></td>';
        var td_tva = '<td style="padding:0" id="td_tva_' + index + '">18.00%</td>';
        var td_remise = '<td style="padding:0;width:10%" id="td_remise_' + index + '"><input class="remise" style="padding:2%;width:80%" type="text" id="gds_ventebundle_' + index + '_taux_remise" type="text" value="0" onkeyup="Test(this)"></td>';
        var td_prix_u_ttc = '<td style="padding:0" id="td_prix_u_ttc_' + index + '"></td>';
        var td_total = '<td style="padding:0;width:10%" id="td_total_' + index + '">0.000</td>';
        var td_delete = '<td style="padding:0" ><img src="/images/icons/delete.png" id="delete_ligne_' + index + '" onclick="delete_ligne(' + index + ')"></td>'
        var tr_contenu = td_num + td_reference + td_designation + hidden_stock + td_qte + td_qte_dispo + td_prix_unitaire_ht + td_tva + td_remise + td_prix_u_ttc + td_total + td_delete;
        var tr = $('<tr id="tr_' + index + '">' + tr_contenu + '</tr>')
        $container.append(tr);
        index++
        nb_article++
        b = tr.attr('id')
        b = b.split('_')
        b = b[1]

        $('#gds_ventebundle_' + b + '_quantite').spinner({
            min: 0,
            max: 10000,
            step: 1,
            places: 2,
            showOn: 'both'
        });
        $('#gds_ventebundle_' + b + '_quantite').keyup(function() {
            var i = $(this).attr('id');
            i = i.split('_');
            i = i[2];
            var quantite = $(this).val();
            var article = getArticleReplaced($('#gds_ventebundle_' + i + '_article').val())
            article.quantite = quantite
            var prix_vente_ht = article.prix_vente;
            var tva = article.taux_tva;
            var remise = article.remise;
            var puttc = prix_vente_ht
            puttc *= (1 + tva / 100)
            puttc *= (1 - remise / 100)
            puttc = puttc.toFixed(3)
            $('#td_prix_u_ttc_' + i).html(puttc);
            var total = puttc * quantite
            $('#td_total_' + i).html(total.toFixed(3));
            resteTtc()
            RefraichirTaxe()
        });
        $('#gds_ventebundle_' + b + '_quantite').change(function() {
            $(this).keyup()
        });
        $('#gds_ventebundle_' + b + '_taux_remise').spinner({
            min: 0,
            max: 100,
            step: 1,
            places: 2,
            showOn: 'both'
        });
        $('#gds_ventebundle_' + b + '_taux_remise').keyup(function() {
            var i = $(this).attr('id');
            i = i.split('_');
            i = i[2];
            doRemiseChange(i)
            resteTtc()
            RefraichirTaxe()
        });
        $('#gds_ventebundle_' + b + '_taux_remise').change(function() {
            $(this).keyup()
        });
        $('#gds_ventebundle_' + b + '_taux_remise').dblclick(function() {
            var i = $(this).attr('id');
            i = i.split('_');
            i = i[2];
            var article = getArticle($('#gds_ventebundle_' + i + '_article').val())
            $.msgBox({
                title: "Dépassement du remise",
                content: "mdp: <input id='mdp' type='password' />",
                type: "confirm",
                buttons: [
                    {type: "submit", value: "Valider"},
                    {type: "cancel", value: "Annuler"}
                ],
                afterShow: function() {
                    $('#mdp').focus()
                },
                success: function(result) {
                    if (result == "Valider") {
                        if ($('#mdp').val() != '') {
                            $.ajax({
                                url: "{{ path('gds_devis_remise_depasse') }}",
                                data: 'pass_remise=' + $('#mdp').val(),
                                success: function(data) {
                                    if (data != 'failed') {
                                        $('#gds_ventebundle_' + i + '_taux_remise').spinner({
                                            min: 0,
                                            max: 100,
                                            step: 1,
                                            places: 2,
                                            showOn: 'both'
                                        });
                                        article.remise_max = 100
                                    }
                                }
                            })
                        }
                    }
                }
            });
        })
        refraichir()
    }
    function add_ligne_from_bl_blanc() {
        var td_num = '<td class="numero_ligne" style="padding:0;text-align:center" id="td_num_' + index + '">' + nb_article + '</td>';
        var hidden_stock = '<input id="gds_ventebundle_' + index + '_article" type="hidden"/>';
        var td_reference = '<td style="padding:0;width:10%" id="td_reference_' + index + '"></td>';
        var td_designation = '<td style="padding:0;width:30%" id="td_designation_' + index + '"></td>';
        var td_qte = '<td style="padding:0;width:10%" id="td_qte_' + index + '"></td>';
        var td_qte_dispo = '<td style="padding:0" id="td_qte_dispo_' + index + '"></td>';
        var td_prix_unitaire_ht = '<td style="padding:0" id="td_prix_unitaire_ht_' + index + '"></td>';
        var td_tva = '<td style="padding:0" id="td_tva_' + index + '">18.00%</td>';
        var td_remise = '<td style="padding:0;width:10%" id="td_remise_' + index + '"></td>';
        var td_prix_u_ttc = '<td style="padding:0" id="td_prix_u_ttc_' + index + '"></td>';
        var td_total = '<td style="padding:0;width:10%" id="td_total_' + index + '">0.000</td>';
        var td_delete = '<td style="padding:0" ></td>'
        var tr_contenu = td_num + td_reference + td_designation + hidden_stock + td_qte + td_qte_dispo + td_prix_unitaire_ht + td_tva + td_remise + td_prix_u_ttc + td_total + td_delete;
        var tr = $('<tr style="height:30px" id="tr_' + index + '">' + tr_contenu + '</tr>')
        $container.append(tr);
        index++
        nb_article++
        refraichir()
    }
    function add_ligne_from_bl_noir() {
        var td_num = '<td class="numero_ligne" style="padding:0;text-align:center" id="td_num_' + index + '">' + nb_article + '</td>';
        var hidden_stock = '<input id="gds_ventebundle_' + index + '_article" type="hidden"/>';
        var td_reference = '<td style="padding:0;width:10%" id="td_reference_' + index + '"></td>';
        var td_designation = '<td style="padding:0;width:30%" id="td_designation_' + index + '"></td>';
        var td_qte = '<td style="padding:0;width:10%" id="td_qte_' + index + '"><input  class="quantite" style="padding:2%;width:80%" type="text" id="gds_ventebundle_' + index + '_quantite" type="text" readonly></td>';
        var td_qte_dispo = '<td style="padding:0" id="td_qte_dispo_' + index + '"></td>';
        var td_prix_unitaire_ht = '<td style="padding:0" id="td_prix_unitaire_ht_' + index + '"></td>';
        var td_tva = '<td style="padding:0" id="td_tva_' + index + '">18.00%</td>';
        var td_remise = '<td style="padding:0;width:10%" id="td_remise_' + index + '"></td>';
        var td_prix_u_ttc = '<td style="padding:0" id="td_prix_u_ttc_' + index + '"></td>';
        var td_total = '<td style="padding:0;width:10%" id="td_total_' + index + '">0.000</td>';
        var td_delete = '<td style="padding:0" ></td>'
        var tr_contenu = td_num + td_reference + td_designation + hidden_stock + td_qte + td_qte_dispo + td_prix_unitaire_ht + td_tva + td_remise + td_prix_u_ttc + td_total + td_delete;
        var tr = $('<tr id="tr_' + index + '">' + tr_contenu + '</tr>')
        $container.append(tr);
        index++
        nb_article++
        var b = tr.attr('id')
        b = b.split('_')
        b = b[1]
        $('#gds_ventebundle_' + b + '_quantite').keyup(function() {
            var i = $(this).attr('id');
            i = i.split('_');
            i = i[2];
            var qte = $(this).val();
            var id = i - 1
            var article = getArticle($('#gds_ventebundle_' + id + '_article').val())
            var x = parseFloat(article.quantite_noir) + parseFloat(article.quantite_blanc) - parseFloat(qte)
            article.quantite_blanc = x
            article.quantite_noir = qte
            $('#td_qte_' + id).html((article.quantite_blanc).toFixed(2))
            var tva = article.taux_tva;
            var remise = article.remise;
            var puttc = article.prix_vente;
            puttc *= (1 + tva / 100)
            puttc *= (1 - remise / 100)
            puttc = puttc.toFixed(3)
            $('#td_prix_u_ttc_' + i).html(puttc);
            var total = puttc * qte
            $('#td_total_' + i).html(total.toFixed(3));
            total = puttc * article.quantite_blanc
            $('#td_total_' + id).html(total.toFixed(3));
            resteTtc()
            RefraichirTaxe()
        });
        $('#gds_ventebundle_' + b + '_quantite').change(function() {
            $(this).keyup()
        });
        refraichir()
    }
    function Test(obj) {
        var data = obj.value;
        var d = data.substring(0, data.length - 1)
        var index_virgule = data.indexOf('.')
        if (index_virgule > 0)
            apres_virgule = data.substring(data.indexOf('.') + 1, data.length)
        if (!TestVerif(data) || apres_virgule.length > 3)
            obj.value = d
    }
    function TestVerif(decimal) {
        var entier = "0123456789"
        var virgule = false
        var first_number = false
        var count_decimal = decimal.length
        for (var index_verif = 0; index_verif < count_decimal; index_verif++) {
            if (entier.indexOf(decimal[index_verif]) < 0) {
                if (decimal[index_verif] == '.' && first_number) {
                    if (virgule)
                        return false
                    else
                        virgule = true
                } else {
                    return false
                }
            } else {
                first_number = true
            }
        }
        return true
    }

    function chercherArticles() {
        $('#td_articles ul').remove()
        $.ajax({
            url: '{{path('gds_vente_get_articles_where_familles')}}',
            data: 'raison_social=' + '{{bonlivraison.client}}',
            success: function(data) {
                $("#articles").tokenInput(data, {
                    preventDuplicates: true,
                    onAdd: function(item) {
                        $('#td_articles').children('.token-input-list').children('.token-input-token').hide()
                        var article = getArticleReplaced(item.id)
                        if (!article) {
                            add_ligne()
                            var article = item.name.split(' : ');
                            var reference = article[0]
                            var designation = article[1]
                            item.quantite = 0
                            var id = index - 1
                            $('#td_reference_' + id).html(reference)
                            $('#td_designation_' + id).html(designation)
                            $('#gds_ventebundle_' + id + '_article').val(item.id)
                            var article = getArticle($('#gds_ventebundle_' + id + '_article').val())
                            if (article) {
                                item.remise = article.remise
                                $('#gds_ventebundle_' + id + '_taux_remise').spinner("destroy");
                                $('#gds_ventebundle_' + id + '_taux_remise').attr('disabled', true)
                            } else {
                                var remise_max = item.remise_max;
                                $('#gds_ventebundle_' + id + '_taux_remise').spinner({
                                    min: 0,
                                    max: remise_max,
                                    step: 1,
                                    places: 2,
                                    showOn: 'both'
                                });
                            }
                            articles_replaced.push(item)
                            remplir_ligne(id, item)
                            setQuantite(id)
                            $('#gds_ventebundle_' + id + '_quantite').keyup()
                        } else {
                            id = article.index
                        }
                    },
                });
            }
        })
    }
    function remplir_ligne(id, item) {
        $('#td_prix_unitaire_ht_' + id).html(item.prix_vente)
        $('#gds_ventebundle_' + id + '_taux_remise').val(item.remise)
        $('#td_tva_' + id).html(item.taux_tva + '%')
    }
    function delete_ligne(index) {
        var article = getArticleReplaced($('#gds_ventebundle_' + index + '_article').val())
        var cmp_delete = 0
        var article_deleted = false
        var count_articles_replaced = articles_replaced.length
        while (!article_deleted && cmp_delete < count_articles_replaced) {
            if (articles_replaced[cmp_delete] == article) {
                articles_replaced.splice(cmp_delete, 1)
                article_deleted = true
            }
            cmp_delete++
        }
        $('#tr_' + index).remove();
        $('.token-input-list li').each(function() {
            var name = article.reference + ' : ' + article.designation
            if ($(this).children("p").html() == name)
                $(this).remove()
        })
        refraichir()
        resteTtc()
        RefraichirTaxe()
    }
    function refraichir() {
        i = 1
        $('.numero_ligne').each(function() {
            $(this).html(i)
            i++
        })
    }
    function getArticle(id) {
        var count_articles = articles.length
        for (var i = 0; i < count_articles; i++) {
            if (articles[i].id == id) {
                return articles[i]
            }
        }
        return null
    }
    function getArticleReplaced(id) {
        var count_articles_replaced = articles_replaced.length
        for (var i = 0; i < count_articles_replaced; i++) {
            if (articles_replaced[i].id == id) {
                return articles_replaced[i]
            }
        }
        return null
    }
    function setQuantite(id) {
        $.ajax({
            url: "{{ path('gds_devis_qte_disponible') }}",
            data: 'reference=' + $('#td_reference_' + id).html() + '&departement=' + '{{bonlivraison.departement}}',
            success: function(data) {
                if (data == 'failed')
                    $('#td_qte_dispo_' + id).html('')
                else {
                    var qte_all = data['qte_all'] + data['qte_all_2']
                    if ($('#departement option:selected').val() == 0) {
                        $('#td_qte_dispo_' + id).html(qte_all)
                    } else {
                        var qte_dep = data['qte'] + data['qte_2']
                        $('#td_qte_dispo_' + id).html("<span class='green'><b>" + qte_dep + "</b></span><span class='red'><b>|</b></span>" + qte_all)
                    }
                }
            }
        })
    }
    function doRemiseChange(i) {
        var article = getArticleReplaced($('#gds_ventebundle_' + i + '_article').val())
        article.remise = $('#gds_ventebundle_' + i + '_taux_remise').val()
        var quantite = article.quantite;
        var prix_vente_ht = article.prix_vente;
        var tva = article.taux_tva;
        var puttc = prix_vente_ht
        puttc *= (1 + tva / 100)
        puttc *= (1 - article.remise / 100)
        puttc = puttc.toFixed(3)
        $('#td_prix_u_ttc_' + i).html(puttc);
        var total = puttc * quantite
        $('#td_total_' + i).html(total.toFixed(3));
    }
    function completerChamp(i) {
        var article = getArticle($('#gds_ventebundle_' + i + '_article').val())
        var quantite = article.quantite_blanc;
        var prix_vente = article.prix_vente;
        var tva = article.taux_tva;
        var remise = article.remise;
        var puttc = prix_vente
        puttc *= (1 + tva / 100)
        puttc *= (1 - remise / 100)
        puttc = puttc.toFixed(3)
        $('#td_prix_u_ttc_' + i).html(puttc);
        var total = puttc * quantite
        $('#td_total_' + i).html(total.toFixed(3));
    }
    function completerChampNoir(i) {
        var id = i - 1
        var article = getArticle($('#gds_ventebundle_' + id + '_article').val())
        var quantite = article.quantite_noir;
        var prix_vente = article.prix_vente;
        var tva = article.taux_tva;
        var remise = article.remise;
        var puttc = prix_vente
        puttc *= (1 + tva / 100)
        puttc *= (1 - remise / 100)
        puttc = puttc.toFixed(3)
        $('#td_prix_u_ttc_' + i).html('');
        $('#td_tva_' + i).html('');
        var total = puttc * quantite
        $('#td_total_' + i).html(total.toFixed(3));
    }
    function RefraichirTaxe() {
        var rowCount_initial = articles.length
        var count_articles = articles.length
        for (var i = 0; i < count_articles; i++) {
            if (articles[i].quantite_noir_begin > 0)
                rowCount_initial++
        }
        var rowCount = $('#lignes_bon_livraison_to_facture tr').length
        var total_ttc = 0
        var taux_tva = new Array();
        var taxes = new Array();
        for (i = 0; i < rowCount; i++) {
            if ($('#td_tva_' + i).html() != null & $('#td_tva_' + i).html() != '') {
                var cmp = taxes.length
                taxes[cmp] = new Array()
                taxes[cmp]['tva'] = 0
                taxes[cmp]['base'] = 0
                taxes[cmp]['montant'] = 0
            }
        }
        var cmp = 0
        var i_refraich = 0
        while (cmp < rowCount_initial) {
            if ($('#td_tva_' + i_refraich).html() != null & $('#td_tva_' + i_refraich).html() != '') {
                var tva = parseFloat($('#td_tva_' + i_refraich).html())
                if (parseFloat($('#td_total_' + i_refraich).html()) > 0) {
                    var j = $.inArray(tva, taux_tva)
                    if (j == -1) {
                        taux_tva.push(tva)
                        j = $.inArray(tva, taux_tva)
                    }
                    var ttc = parseFloat($('#td_total_' + i_refraich).html())
                    total_ttc += ttc
                    var ht = ttc / (1 + tva / 100)
                    var montant = ht * tva / 100
                    taxes[j]['tva'] = tva
                    taxes[j]['base'] += ht
                    taxes[j]['montant'] += montant
                }
            }
            cmp++
            i_refraich++
        }
        i_refraich = rowCount_initial
        cmp = rowCount_initial + 1
        while (cmp < rowCount) {
            if ($('#td_total_' + i_refraich).html() != null) {
                var tva = parseFloat($('#td_tva_' + i_refraich).html())
                if (parseFloat($('#td_total_' + i_refraich).html()) > 0) {
                    var j = $.inArray(tva, taux_tva)
                    if (j == -1) {
                        taux_tva.push(tva)
                        j = $.inArray(tva, taux_tva)
                    }
                    ttc = parseFloat($('#td_total_' + i_refraich).html())
                    total_ttc += ttc
                    ht = ttc / (1 + tva / 100)
                    montant = ht * tva / 100
                    taxes[j]['tva'] = tva
                    taxes[j]['base'] += ht
                    taxes[j]['montant'] += montant
                }
                cmp++
            }
            i_refraich++
        }
        taxes = TriTab(taux_tva, taxes)
        $('#taxe_body2 tr').remove()
        var totaux = 0
        var count_tva = taux_tva.length
        for (i = 0; i < count_tva; i++) {
            tva = taxes[i]['tva'].toFixed(2)
            totaux += taxes[i]['montant']
            $('#taxe_body2').append('<tr id="tr_taxe_' + tva + '_2"><td id="taxe_' + tva + '_2">' + tva + '%</td><td id="base_' + tva + '_2">' + taxes[i]['base'].toFixed(3) + '</td><td id="montant_taxe_' + tva + '_2">' + taxes[i]['montant'].toFixed(3) + '</td></tr>');
        }
        $('#taxe_body2').append('<tr><td>Totaux</td><td></td><td id="total_taxe2">' + totaux.toFixed(3) + '</td></tr>');
        $('#montant_total').html(total_ttc.toFixed(3))
        total_ttc += {{timbre}}
        $('#montant_total_ttc').html(total_ttc.toFixed(3))
    }
    function getTaxeInitial() {
        var rowCount = articles.length
        var count_articles = articles.length
        for (var i = 0; i < count_articles; i++) {
            if (articles[i].quantite_noir > 0)
                rowCount++
        }
        var total_ttc = 0
        var taux_tva = new Array();
        var taxes = new Array();
        for (i = 0; i < rowCount; i++) {
            taxes[i] = new Array()
            taxes[i]['tva'] = 0
            taxes[i]['base'] = 0
            taxes[i]['montant'] = 0
        }
        var cmp = 0
        var i_refraich = 0
        while (cmp < rowCount) {
            if ($('#td_total_' + i_refraich).html() != null) {
                if ($('#td_tva_' + i_refraich).html() == '') {
                    var i_refraich2 = i_refraich - 1
                    var tva = parseFloat($('#td_tva_' + i_refraich2).html())
                } else
                    var tva = parseFloat($('#td_tva_' + i_refraich).html())
                if (parseFloat($('#td_total_' + i_refraich).html()) > 0) {
                    j = $.inArray(tva, taux_tva)
                    if (j == -1) {
                        taux_tva.push(tva)
                        j = $.inArray(tva, taux_tva)
                    }
                    var ttc = parseFloat($('#td_total_' + i_refraich).html())
                    total_ttc += ttc
                    var ht = ttc / (1 + tva / 100)
                    var montant = ht * tva / 100
                    taxes[j]['tva'] = tva
                    taxes[j]['base'] += ht
                    taxes[j]['montant'] += montant
                }
                cmp++
            }
            i_refraich++
        }
        taxes = TriTab(taux_tva, taxes)
        $('#taxe_body tr').remove()
        var totaux = 0
        var count_tva = taux_tva.length
        for (var i = 0; i < count_tva; i++) {
            tva = taxes[i]['tva'].toFixed(2)
            totaux += taxes[i]['montant']
            $('#taxe_body').append('<tr id="tr_taxe_' + tva + '"><td id="taxe_' + tva + '">' + tva + '%</td><td id="base_' + tva + '">' + taxes[i]['base'].toFixed(3) + '</td><td id="montant_taxe_' + tva + '">' + taxes[i]['montant'].toFixed(3) + '</td></tr>');
        }
        $('#taxe_body').append('<tr><td>Totaux</td><td></td><td id="total_taxe">' + totaux.toFixed(3) + '</td></tr>');
        $('#montant_total_ancien').html(total_ttc.toFixed(3))
    }
    function resteTtc() {
        var montant1 = 0
        var count_articles = articles.length
        for (var i = 0; i < count_articles; i++) {
            var article = articles[i]
            var qte = (article.quantite_noir)
            var prix_vente = (article.prix_vente)
            var remise = (article.remise)
            var taux_tva = (article.taux_tva)
            var mont = qte * prix_vente * (1 - remise / 100) * (1 + taux_tva / 100)
            mont = mont.toFixed(3)
            montant1 += parseFloat(mont)
        }
        var montant2 = 0
        var count_articles_replaced = articles_replaced.length
        for (var i = 0; i < count_articles_replaced; i++) {
            var article = articles_replaced[i]
            var qte = article.quantite
            var prix_vente = article.prix_vente
            var remise = article.remise
            var taux_tva = article.taux_tva
            var mont = qte * prix_vente * (1 - remise / 100) * (1 + taux_tva / 100)
            mont = mont.toFixed(3)
            montant2 += parseFloat(mont)
        }
        var montant = montant1 - montant2
        $('#td_reste').html(montant.toFixed(3))
    }
    function setTousQuantite() {
        var references = new Array()
        var iis = new Array()
        var cmp = 0
        $('#lignes_bon_livraison_to_facture tr').each(function() {
            var ii = $(this).attr('id');
            ii = ii.split('_');
            ii = ii[1]
            if ($('#td_reference_' + ii).html() != '' && $('#td_reference_' + ii).html() != null) {
                references[cmp] = $('#td_reference_' + ii).html()
                iis[cmp] = ii
                cmp++
            }
        })
        $.ajax({
            url: "{{ path('gds_devis_all_qte_disponible') }}",
            data: 'references=' + JSON.stringify(references) + '&departement=' + '{{bonlivraison.departement}}',
            success: function(data) {
                var count_lines = iis.length
                for (var i = 0; i < count_lines; i++) {
                    var qte_all = data[i]['qte_all'] + data[i]['qte_all_2']
                    if ($('#departement option:selected').val() == 0) {
                        $('#td_qte_dispo_' + iis[i]).html(qte_all)
                    } else {
                        var qte_dep = data[i]['qte'] + data[i]['qte_2']
                        $('#td_qte_dispo_' + iis[i]).html("<span class='green'><b>" + qte_dep + "</b></span><span class='red'><b>|</b></span>" + qte_all)
                    }
                }

            }
        })
    }
</script>
<input type="hidden" id="heure"/>